package com.xxh.shirodemon.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //shiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean Bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        Bean.setSecurityManager(securityManager);

        //设置shiro的内置过滤器
        /*
        * anon:无需认证
        * authc :必须认证才能访问
        * perms:有某个资源的访问权限
        * role:有某个角色权限才可访问
        * */
        Map<String,String>filterMap=new LinkedHashMap<>();


        //授权(user:add表示权限名字，/user/add访问需要 user:add权限)
        filterMap.put("/user/add","perms[user:add]");

        //授权(/user/update需要user:update的权限)
        filterMap.put("/user/update","perms[user:update]");

        //拦截所有user请求(所有/user 请求都需要认证才能访问)
        filterMap.put("/user/*","authc");
        Bean.setFilterChainDefinitionMap(filterMap);
        //设置登录页面
        Bean.setLoginUrl("/toLogin");

        //设置未授权页面
        Bean.setUnauthorizedUrl("/noauth");
        return Bean;
    }

    //DefaultWebSecurityManager
    @Bean(name = "SecurityManager")
    public DefaultWebSecurityManager getDefaultSecurityManager(@Qualifier("userRealm") UserRealm realm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        //关联realm
        manager.setRealm(realm);
        return manager;
    }

    //创建realm对象，需要自定义类
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //整合Shiro和Thymeleaft

    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
